<template>
  <div :class="`element-template-${element.id}`" v-html="content"></div>
</template>

<script>
import { Vue, Component, Prop, Watch} from 'vue-property-decorator'
import bestTemplate from "best-template"
@Component
export default class ElementTemplate extends Vue {
  @Prop(Object) element:any
  styleDom=null
  get compile () {
    try {
      return bestTemplate.compile(this.element.extra.template)
    } catch (e) {
      console.error(e)
    }
  }

  get content () {
    try {
      return this.compile(this.element.data.source)
    } catch (e) {
      console.error(e)
    }
  }

  get style () {
    let style = this.element.extra.style
    if (this.element.extra.scoped) {
      return `.element-template-${this.element.id} ` + style.replace(/^[\s]*/, "").replace(/([}\n\r]+)([^{]+)\{/, ($, $1, $2) => {
        return $1 + `.element-template-${this.element.id} ` + $2 + "{"
      })
    }
    return style
  }

  @Watch("element")
  onStyleChanged ():void {
    this.styleDom.innerHTML = this.style
  }

  mounted ():void {
    this.styleDom = document.createElement('style')
    document.querySelector("head").appendChild(this.styleDom)
    this.styleDom.setAttribute("class", "template-style-" + this.element.id)
    this.styleDom.setAttribute("type", "text/css")
    this.styleDom.innerHTML = this.style
  }
}
</script>
